package cn.wolfcode.web.interceptor;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.Permission;
import cn.wolfcode.qo.JsonResult;
import cn.wolfcode.util.RequiredPermission;
import cn.wolfcode.util.UserContext;
import com.alibaba.fastjson.JSON;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;


public class CheckPermissionInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod){
            Employee employee = UserContext.getCurrentUser();
            if (employee.getAdmin()!=null&&employee.getAdmin()){
                return true;
                }
                HandlerMethod method=(HandlerMethod)handler;

                //获取当前请求方法上的注解
            RequiredPermission methodAnnotation = method.getMethodAnnotation(RequiredPermission.class);
                    if (methodAnnotation==null){
                        return true;
                    }
            List<String> permissions = (List<String>) request.getSession().getAttribute(UserContext.PERMISSION_SESSION_NAME);
            String expermission = methodAnnotation.expermission();
            if (permissions.contains(expermission)){
                return true;
            }
            ResponseBody annotation = method.getMethodAnnotation(ResponseBody.class);
                if (annotation==null){
                 response.sendRedirect("/nopermission");
                }else {
                    response.setContentType("application/json;charset=utf-8");
                    String resPonseData = JSON.toJSONString(new JsonResult(false, "您没有权限操作"));
                        response.getWriter().write(resPonseData);
                }
                return false;
        }
        return true;
    }
}
